import Notice from '../../../Models/notice';
import Point from '../../../Models/point';
import {constantObj} from '../../../utils/constants'
import User from '../../../Models/user';
import moment from 'moment';
import qs from 'qs';

const crypto = require('crypto');
const SHA256 = require("crypto-js/sha256");
const userEntity = new User();
const pointEntity = new Point();

export function saveNotice (notice) {
  const noticeEntity = new Notice();
  noticeEntity.saveNotice(notice);
}

export function getNewPoints (creatorId, desc, score) {
  pointEntity.getAllPoints({creatorId, dayString: moment().format('YYYY-MM-DD'), desc}, (err, points)=>{
    if(err){
        return;
    }
    // if(!points || points.length < constantObj[desc]) {
    if(!points) {
      const pointEntity = new Point();
      pointEntity.savePoint({creatorId, score, desc}, (err)=>{
        userEntity.getUser({
          _id: creatorId
        },(err,user)=>{
            if(err){
              return;
            }
            if (!user) {
              return;
            }
            const point = (user._doc.point || 0) + score;
            const leftPoint = (user._doc.leftPoint || 0) + score;
            userEntity.updateUser({
                _id: creatorId,
                point,
                leftPoint
            }, err=>{
              console.log(err)
            })
        })
      })
    }
  })
}

export function getPayData(prod_name, occur_balance, summary, channel_id = '021', receive_url){
  const dateString = moment().format('YYYYMMDD HHmmss');
  const [partner_trans_date, partner_trans_time] = dateString.split(' ');
  const partner_id = channel_id === '021'?'40000039':'40000040'
  const data = {
      partner_id,
      partner_serial_no: partner_trans_date+partner_trans_time+Math.random().toString(10).substr(2,8),
      partner_trans_date, partner_trans_time, 
      prod_name,
      currency_code: "CNY",
      occur_balance, 
      summary,
      channel_id, 
      receive_url,
      targetcomp_id: 91000
  }

  const msg = qs.stringify(data, { encode: false, charset: 'utf-8', sort: (a, b)=>a.localeCompare(b) });
  const signSHA = SHA256(msg).toString().toUpperCase()
  const sign = crypto.createSign('RSA-SHA1');
  sign.update(signSHA);
  const cert_sign = sign.sign(constantObj.privateKey, 'base64');
  data.cert_sign = cert_sign;
  return qs.stringify(data, { encode: true, charset: 'utf-8', sort: (a, b)=>a.localeCompare(b) })
}